/**
 * @file localStorage操作
 * @author xiazhiyao<xiazhiyao@baijia.com>
 */

export default {
    // 默认采用localStorage方式
    localStorage: window.localStorage,

    /**
     * 获取本地存储值
     *   localStorage存在key，获取，没有直接返回undefined
     *   key对应的value非false，JSON.parse处理
     *
     * @param  {string}   key      存储key值
     * @param  {Function} callback 回调函数
     * @return {*}                 返回值
     */
    get(key, callback) {
        let result;

        if (this.localStorage[key]) {
            result = this.localStorage.getItem(key);
            if (result) {
                result = JSON.parse(result);
            }
        }

        if (typeof callback === 'function') {
            return callback(result);
        }

        return result;
    },

    /**
     * 设置本地存储
     *
     * @param {string}   key      [description]
     * @param {*}   value    [description]
     * @param {Function} callback [description]
     */
    set(key, value, callback) {
        if (typeof value !== 'undefined') {
            value = JSON.stringify(value);
            this.localStorage.setItem(key, value);
        }

        if (typeof callback === 'function') {
            return callback(value);
        }
    },

    remove(key, callback) {
        this.localStorage.removeItem(key);
        if (typeof callback === 'function') {
            return callback();
        }
    },

    clear() {
        this.localStorage.clear();
    }
};
